const { wxConfig } = require("../../../config/application.config.js");
const axios = require("axios");

module.exports = {
  // 根据appId和appSecret获取access_token
  getAccessToken: () => {
    return new Promise((resolve, reject) => {
      const { appId, appSecret } = wxConfig;
      const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
      axios
        .get(url)
        .then(({ data }) => {
          if (data.access_token) {
            resolve(data.access_token);
          } else {
            reject("获取access_token失败");
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 根据code和access_token获取用户手机信息
  getUserPhoneNumber(code, access_token) {
    return new Promise((resolve, reject) => {
      const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${access_token}`;
      axios({
        method: "post",
        url,
        data: {
          code,
        },
      })
        .then(({ data }) => {
          if (data.errcode === 0) {
            resolve(data.phone_info.phoneNumber);
          }
          reject(data.errmsg);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
};
